package hook

import (
	"fmt"
	"gitee.com/kudingc/zh_logs/library/email"
	log "github.com/sirupsen/logrus"
	"os"
	"strings"
)

var (
	emailTitle  string       // 邮件标题
	emailSender email.Sender // 邮件发送者（或者叫邮件服务器）信息
)

type EmailSubscribeMap map[log.Level][]*email.Receiver

type EmailSubscribeHook struct {
	subMap EmailSubscribeMap
}

func InitEmailSubscribe(title string, sender email.Sender) {
	emailTitle = title
	emailSender = sender
}

// Levels 此处可以自实现hook 目前使用三方hook
func (h *EmailSubscribeHook) Levels() []log.Level {
	return log.AllLevels
}

func (h *EmailSubscribeHook) Fire(entry *log.Entry) error {
	for level, receivers := range h.subMap {
		//命中 准备消费
		if level == entry.Level {
			if len(receivers) > 0 {
				serialized, err := entry.Logger.Formatter.Format(entry)
				if err != nil {
					fmt.Fprintf(os.Stderr, "Failed to obtain reader, %v\n", err)
				} else {
					email.SendEmail(emailSender, receivers, emailTitle, fmt.Sprintf("%s:[系统日志警报]", emailTitle+entry.Level.String()),
						fmt.Sprintf("日志内容: %s", serialized))
				}
			}
		}
	}
	return nil
}

// NewEmailSubscribeMap 创建订阅日志类型及邮件地址，如果有多个邮件地址，用分号隔开
func NewEmailSubscribeMap(level log.Level, receiverStr string) EmailSubscribeMap {
	subMap := EmailSubscribeMap{}
	addressList := strings.Split(receiverStr, ";")
	var receivers []*email.Receiver
	for _, address := range addressList {
		receivers = append(receivers, &email.Receiver{Email: address})
	}
	subMap[level] = receivers
	return subMap
}

func NewEmailSubscribeHook(subMap EmailSubscribeMap) *EmailSubscribeHook {
	return &EmailSubscribeHook{subMap}
}
